package cn.wolfcode.car.controller;

import cn.wolfcode.car.ann.RequiredPermission;
import cn.wolfcode.car.context.UserContext;
import cn.wolfcode.car.domain.*;
import cn.wolfcode.car.qo.EmployeeQueryObject;
import cn.wolfcode.car.service.IDepartmentService;
import cn.wolfcode.car.service.IEmployeeRoleService;
import cn.wolfcode.car.service.IEmployeeService;
import cn.wolfcode.car.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import result.JsonResult;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IEmployeeRoleService employeeRoleService;

    @PostMapping("/checkUserName")
    @ResponseBody
    public Map<String, Object> checkUserName(String username) {
        Map<String, Object> map = new HashMap<>();
        Employee employee = employeeService.getByUserName(username);
        map.put("valid", employee == null);
        return map;
    }


    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {
        PageInfo<Employee> list = employeeService.list(qo);
        System.out.println(list);
        model.addAttribute("result", list);
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);
//     /   int a = 10;
//        int b = 0;
//        System.out.println(a / b);
        return "employee/list";
    }

    @PostMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee employee, Long[] ids) {
        if (employee.getId() == null) {

            employeeService.save(employee);
        } else {
            employeeService.update(employee);
            //先删除所有,再新增
            employeeRoleService.deleteByEmployeeId(employee.getId());
        }
        if (ids != null) {
            for (Long id : ids) {
                EmployeeRole employeeRole = new EmployeeRole(employee.getId(), id);
                employeeRoleService.save(employeeRole);
            }
        }
        return "redirect:/employee/list";
    }

    @GetMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        employeeService.delete(id);
        return JsonResult.success(null);
    }

    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) {
            //编辑
            Employee employee = employeeService.get(id);
            model.addAttribute("currentEmployee", employee);
            List<Role> currentRoles = roleService.listByEmployeeId(id);
            model.addAttribute("currentRoles", currentRoles);
        }
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);
        List<Role> roles = roleService.listAll();
        model.addAttribute("roles", roles);
        return "employee/input";
    }

    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws Exception {
        //文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        response.setHeader("Content-Disposition", "attachment;filename=employee.xls");
        //创建excel文件
        Workbook wb = employeeService.exportXls();
        //把excel的数据输出给浏览器
        wb.write(response.getOutputStream());
    }

    @RequestMapping("/importXls")
    public String importXls(MultipartFile file) throws IOException {
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读sheet one
        Sheet sheet = wb.getSheetAt(0);
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            String username = row.getCell(0).getStringCellValue();
            String name = row.getCell(1).getStringCellValue();
            String password;
            if (row.getCell(3).getCellType() == CellType.NUMERIC) {
                password = row.getCell(3).getNumericCellValue() + "";
            } else {
                password = row.getCell(3).getStringCellValue();
            }
            String email = row.getCell(4).getStringCellValue();
            int age = (int) row.getCell(5).getNumericCellValue();
            boolean admin = row.getCell(6).getBooleanCellValue();
            long deptId = (long) row.getCell(7).getNumericCellValue();


//            Employee employee = new Employee(null, username, name, password, email, age, admin, new Department(deptId, null, null, null, null, null, null), null, null, null, null, null);
//            employeeService.save(employee);
        }
        return "redirect:/employee/list";
    }


    @RequestMapping("/deleteAll")
    @ResponseBody
    public Object deleteAll(Long[] ids) {
        employeeService.deleteAll(ids);
        return JsonResult.success(null);
    }

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);

        SecurityUtils.getSubject().login(usernamePasswordToken);
        return JsonResult.success(null);

    }

    @ResponseBody
    @RequestMapping("/testpermission")
    public String test() {
        Subject subject = SecurityUtils.getSubject();
        System.out.println(subject.isPermitted("employee:delete"));//返回 true false
        subject.checkPermission("employee:delete");//抛没有权限异常

        System.out.println("----");
        if (subject.hasRole("admin")) {
            return "1";
        } else {
            return "0";
        }
    }
//    @ResponseBody
//    @RequestMapping("/login")
//    public Object login(String username, String password, HttpSession session) {
//        Employee employee = employeeService.getByUserName(username);
//        if (employee == null) {
//            return JsonResult.error("用户名不存在");
//        } else {
//            //if (password.equals(employee.getPassword())) {
//            if (1 == 1) {
//                //存储用户信息
//                System.out.println("user=>>>>>>>>"+employee);
//                UserContext userContext = new UserContext();
//                userContext.setEmployee(employee);
//                //存储权限
//                List<Role> roles = employeeService.getRolesAndPermission(employee.getId());
//                List<Permission> permissions = employeeService.getPermission(employee.getId());
//                userContext.setRoles(roles);
//                userContext.setPermissions(permissions);
//                session.setAttribute("userContext", userContext);
//
//                return JsonResult.success(employee);
//            } else {
//                return JsonResult.error("密码错误");
//            }
//        }
//    }
}
